/**
 * \license
 * Copyright Lassi Marttala 2013
 * 
 * This file is part of dlt2jpa.
 *
 * dlt2jpa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dlt2jpa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dlt2jpa.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.fizzl.dlt;

import java.io.IOException;
import java.io.InputStream;

import net.fizzl.dlt.message.DltMessage;
import net.fizzl.dlt.message.parser.DltMessageParser;

public class DltStreamReader {
	public DltStreamReader(InputStream is) {
		this.is = is;
	}

	DltMessage read() throws IOException {
		byte readbuffer[] = new byte[256];
		DltMessage ret = null;
		int read;
		do {
			read = is.read(readbuffer);
			buffer(readbuffer);
			ret = parseBuffer(); 
			
		} while(read > 0 && ret == null);
		return ret;
	}
	
	void buffer(byte buf[]) {
		currentBuffer = ByteArrayUtils.concat(buf, currentBuffer);
	}
	
	DltMessage parseBuffer() {
		return parser.fromByteArray(currentBuffer);
	}
	
	
	byte currentBuffer[] = new byte[0];
	DltMessageParser parser = new DltMessageParser();
	InputStream is;
}
